package com.kedll.library.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.database.DataSetObserver;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Matrix;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.TranslateAnimation;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.kedll.library.R;
import com.kedll.library.adapter.TabBarAdapter;
import com.kedll.library.listener.ISelection;
import com.kedll.library.listener.OnItemChangedListener;
import com.kedll.library.util.MyUtils;

import java.util.Arrays;


public class TabBar extends LinearLayout {

    private int DEV = 4;
    protected ImageView cursor;// 动画图片

    protected int offset = 0;// 动画图片偏移量
    protected int currIndex = 0;// 当前页卡编号
    protected int origin = 0;//定义初始位置
    protected int bmpW;// 动画图片宽度
    protected int one = 0;
    private ISelection onSelectionListener = null;
    /**
     * Tab根布局对象
     */
    protected View v = null;
    /**
     * Tab项布局对象
     */
    protected ViewGroup tabContent = null;
    /**
     * 游标布局对象
     */
    protected ViewGroup cursorContent = null;
    protected BaseAdapter adapter;
    private int cursorID;
    protected int mLayoutResource;
    private AnimationListener animationListener;

    private DataSetObserver mDataObserver = new DataSetObserver() {

        @Override
        public void onChanged() {
            refresh();
        }

        @Override
        public void onInvalidated() {
            refresh();
        }

    };

    public void setAnimationListener(AnimationListener animationListener) {
        this.animationListener = animationListener;
    }

    public TabBar(Context context, AttributeSet attrs) {
        super(context, attrs);

        // TODO Auto-generated constructor stub

        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.TabBar);
        DEV = a.getInt(R.styleable.TabBar_dev, 4);
        origin = a.getInt(R.styleable.TabBar_origin, 0);
        cursorID = a.getResourceId(R.styleable.TabBar_cursor, 0);
        mLayoutResource = a.getResourceId(R.styleable.TabBar_tabLayout, 0);
        if (mLayoutResource == 0) {
            throw new IllegalArgumentException("mLayoutResource is not be null");
        }
        a.recycle();

        init(context, origin);

    }

    public TabBar(Context context) {
        this(context, null);
        // TODO Auto-generated constructor stub
    }

    /**
     * @param context
     * @param index
     */
    public TabBar(Context context, int index) {
        super(context);
        init(context, index);
    }

    public TabBar(Context context, int index, int dev) {
        super(context);
        setDEV(dev);
        init(context, index);
    }

    public TabBar(Context context, int index, int dev, int cursor) {
        super(context);
        setDEV(dev);
        this.cursorID = cursor;
        init(context, index);
    }

    private void init(Context context, int origin) {
        initView(context);
        if (cursorID != 0)
            cursor.setImageResource(cursorID);

        addView(v, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

        this.origin = origin;
        //		initCursor(getContext(), origin);
        if (adapter != null)
            setAdapter(adapter);
    }

    public void initView(Context context) {
        v = LayoutInflater.from(context).inflate(mLayoutResource, null);
        tabContent = (ViewGroup) v.findViewById(R.id.tab);
        cursor = (ImageView) v.findViewById(R.id.cursor);
        cursorContent = (ViewGroup) v.findViewById(R.id.cursor_content);
    }

    public View getChildAtIndex(int index) {
        if (tabContent == null)
            return null;
        return tabContent.getChildAt(index);
    }

    /**
     * 设置数据
     *
     * @param adapter
     */
    public void setAdapter(BaseAdapter adapter) {
        if (this.adapter != null) {
            this.adapter.unregisterDataSetObserver(mDataObserver);
        }

        this.adapter = adapter;
        if (this.adapter != null) {
            this.adapter.registerDataSetObserver(mDataObserver);
        }
        bindLinearLayout();
    }

    /**
     * 刷新数据列表
     */
    public void refresh() {
        if (adapter == null)
            return;
        bindLinearLayout();
    }

    public View getCursor() {
        return cursor;
    }

    /**
     * 绑定布局
     * 当Tab项的数量比较多，需要用用到横向的ScorllView时，给定每项Tab的宽度
     */
    public void bindLinearLayout() {
        int count = adapter.getCount();
        tabContent.removeAllViews();
        cursorContent.removeAllViews();
        LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        layoutParams.weight = 1;
        //        layoutParams.width = 0;
        if (count == 0)
            return;
        for (int i = 0; i < count; i++) {
            View v = adapter.getView(i, null, null);

            v.setOnClickListener(new MyOnClickListener(i));
            LayoutParams params = (LayoutParams) v.getLayoutParams();
            if (params == null) {
                params = layoutParams;
                this.tabContent.addView(v, i, params);
            }
            this.tabContent.addView(v, i, params);
            View view;
            if (i == origin) {
                view = cursor;
            } else {
                view = new View(getContext());
            }
            this.cursorContent.addView(view, i, params);
        }
        setDEV(count);
    }

    /**
     * @param context
     */
    protected void initCursor(Context context, int origin) {
        int screenW = getMeasuredWidth();
        offset = (screenW / DEV /*- bmpW*/) / 2;// 计算偏移量
        one = offset * 2 /*+ bmpW*/;

        setOrigin(origin);
    }

    public TabBarAdapter setData(int arrayId, int origin) {
        if (origin < 0) {
            origin = 0;
        }
        String[] datas = getResources().getStringArray(arrayId);
        int widthPx = (MyUtils.getScreenWidth(getContext()) - getPaddingLeft() - getPaddingRight()) / datas.length;
        TabBarAdapter tabBarAdapter = new TabBarAdapter(getContext(), Arrays.asList(datas), widthPx);
        setAdapter(tabBarAdapter);
        setOrigin(origin);
        setSelection(origin);
        return tabBarAdapter;
    }

    public TabBarAdapter setData(int arrayId) {
        return setData(arrayId, 0);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // TODO 自动生成的方法存根
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        if (offset == 0)
            initCursor(getContext(), origin);

    }

    public int getCursorWidth() {
        // TODO Auto-generated method stub
        Options options = new Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(getResources(), cursorID, options);
        return options.outWidth;
    }


    public void onPageSelected(int arg0) {
        Animation animation = null;
        animation = onCreaterAnimation(arg0 - origin);

        currIndex = arg0 - origin;
        if (animation != null) {
            animation.setFillAfter(true);// True:图片停在动画结束位置
            animation.setDuration(100);
            cursor.startAnimation(animation);
        }

        invalidate();
        requestLayout();
    }

    /**
     * 创建导航栏移动动画
     *
     * @param arg0 要移动到的目标
     * @return
     */
    @SuppressLint("NewApi")
    private Animation onCreaterAnimation(int arg0) {
        Animation animation = null;
        if (currIndex == 0) {
            animation = new TranslateAnimation(0, one * arg0, 0, 0);
        } else {
            animation = new TranslateAnimation(one * currIndex, one * arg0, 0, 0);
        }
        if (animationListener != null)
            animation.setAnimationListener(animationListener);
        return animation;

    }


    /**
     * 头标点击监听
     */
    public class MyOnClickListener implements OnClickListener {
        private int index = -1;

        public MyOnClickListener(int i) {
            index = i;
        }

        public void onClick(View v) {
            setSelection(v, index);
        }
    }

    public void setOnSelectionListener(ISelection onSelectionListener) {
        this.onSelectionListener = onSelectionListener;
    }

    public ISelection getOnSelectionListener() {
        return onSelectionListener;
    }

    public void setDEV(int dEV) {
        offset = 0;
        DEV = dEV;
        requestLayout();
    }

    public int getDEV() {
        return DEV;
    }

    public void setOrigin(int origin) {
        this.origin = origin;
        Matrix matrix = new Matrix();
        if (origin == 0) {
            matrix.postTranslate(offset, 0);
        } else {
            matrix.postTranslate(one * origin, 0);
        }
        if (cursor == null)
            return;
        cursor.setImageMatrix(matrix);// 设置动画初始位置
        cursorContent.removeView(cursor);
        cursorContent.addView(cursor, origin);
    }

    public int getCurrentIndex() {
        return currIndex + origin;
    }

    public void setSelection(int index) {
        setSelection(tabContent.getChildAt(index), index);
    }

    public void setSelection(View v, int index) {
        setItemSelection(index);
        if (onSelectionListener != null) {
            onSelectionListener.selection(v, index);
        }
    }

    public void setItemSelection(int index) {
        if (index < 0) {
            index = 0;
        }
        int count = adapter == null ? 0 : adapter.getCount();
        for (int i = 0; i < count; i++) {
            Object obj = getItem(i);
            if (obj instanceof OnItemChangedListener) {
                OnItemChangedListener view = (OnItemChangedListener) obj;
                if (i == index) {
                    view.setSelectable(true);
                } else {
                    view.setSelectable(false);
                }
            } else {
                throw new IllegalArgumentException("child item must implements OnItemChangedListener");
            }
        }
        if(index != getCurrentIndex())
        onPageSelected(index);
    }

    /**
     * 获取对应的数据
     *
     * @param index
     * @return
     */
    public Object getItem(int index) {
        return tabContent.getChildAt(index);
    }
}
